package leetcode.medium.limit50;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 三树之和
 *
 * @author yaoyao1.liu@zhaopin.com.cn
 * @since 2022-06-30 10:54
 **/
public class No15 {
    public static void main(String[] args) {
        No15 no15 = new No15();
        int[] nums = new int[]{0, 0, 0, 0};
        List<List<Integer>> list = no15.threeSum(nums);
        System.out.println(list);
    }

    public List<List<Integer>> threeSum(int[] nums) {
        int length = nums.length;
        Arrays.sort(nums);
        List<List<Integer>> list = new ArrayList<>();
        for (int first = 0; first < length; first++) {
            int a = nums[first];
            if (first > 0 && nums[first] == nums[first - 1]) {
                continue;
            }
            int third = length - 1;
            int target = -nums[first];
            for (int second = first + 1; second < length; second++) {
                if (second > first + 1 && nums[second] == nums[second - 1]) {
                    continue;
                }
                while (second < third && nums[second] + nums[third] > target) {
                    --third;
                }
                if (second == third) {
                    break;
                }
                if (nums[second] + nums[third] == target) {
                    List<Integer> zeroList = new ArrayList<>();
                    zeroList.add(nums[first]);
                    zeroList.add(nums[second]);
                    zeroList.add(nums[third]);
                    list.add(zeroList);
                }
            }
        }
        return list;
    }
}
